import json
import logging

from google.appengine.api import channel
from google.appengine.ext import db

from lib import cache


class AuthKey(cache.Model):
  auth_key = db.ByteStringProperty(required=True)
  live = db.BooleanProperty(required=True, default=True)


class Account(cache.Model):
  user = db.UserProperty()
  created = db.DateTimeProperty(required=True, auto_now_add=True)


class Channel(db.Model):
  account = db.ReferenceProperty(required=True, reference_class=Account)
  client_id = db.ByteStringProperty(required=True)
  token = db.ByteStringProperty(required=True)
  active = db.BooleanProperty(required=True, default=False)
  last_seen = db.DateTimeProperty(required=True, auto_now=True)

  def SendMessage(self, message_type, feed=None, value=None):
    msg = json.dumps({
      'type': message_type,
      'feed': feed,
      'value': value,
    })
    channel.send_message(self.client_id, msg)


class Feed(db.Model):
  path = db.StringProperty(required=True)
  active = db.BooleanProperty(required=True, default=False)
  etag = db.StringProperty()


class Subscription(db.Model):
  feed = db.ReferenceProperty(required=True, reference_class=Feed)
  channel = db.ReferenceProperty(required=True, reference_class=Channel)


class Media(db.Model):
  feed = db.ReferenceProperty(required=True, reference_class=Feed)
  source_id = db.StringProperty(required=True)
  title = db.StringProperty(required=True)
  description = db.TextProperty(required=True)
  duration_seconds = db.IntegerProperty(required=True)

  def to_dict(self):
    ret = db.to_dict(self)
    del ret['feed']
    return ret
